<template>
  <div class="project-type-dynamic-info">
    <!-- 动态信息 -->
    <base-timeline :data="recordPage.list" :record-render="renderRecord" :loading="recordLoading" :loadmore="recordPage.hasNextPage" @load="loadMore" />
  </div>
</template>
<script>
import Page from '@model/Page';
import { isOpenData } from '@src/util/platform';
// api
import { projectRecordList } from '@src/api/ProjectManage.ts';
import { t } from '@src/locales';
import { openTab } from '@src/platform'
import { statusObj } from '@src/modules/projectManage/productTypeUtils/fixFields.js';

export default {
  name: 'project-type-dynamic-info',
  props: {
    templateId: {
      type: Number | String,
      default: '',
    },
    projectId: {
      type: String | Number,
      default: '',
    },
    taskId: {
      type: String | Number,
      default: '',
    },
  },
  data() {
    return {
      recordLoading: false,
      recordPage: new Page(), // 页面数据
      params: {
        projectId: this.projectId,
        taskId: this.taskId,
        pageNum: 1,
        pageSize: 15,
      },
    };
  },
  mounted() {
    this.searchRecord();
  },
  methods: {
    // 获取动态信息
    getRecordList(params) {
      return projectRecordList(params);
    },

    // 查询信息动态
    async searchRecord() {
      try {
        this.recordLoading = true;
        let res = await this.getRecordList(this.params);

        this.recordPage.list = [];
        let result = res?.data || {};

        this.recordPage.merge(result);
        this.$emit('getRecordCount', result.total);
      } catch (error) {
        console.error(`searchRecord ${error}`);
      } finally {
        this.recordLoading = false;
      }
    },

      
  openTriggerTab(jumpUrl) {
    const fromId = window?.frameElement?.getAttribute('id') || ''
    openTab({
      title: t('common.base.isLoading2'),
      id: jumpUrl,
      url: jumpUrl,
      fromId,
      close: true
    })
    
  },

    // 加载更多
    async loadMore() {
      try {
        this.params.pageNum++;
        this.recordLoading = true;

        let res = await this.getRecordList(this.params);
        let result = res.data || {};

        this.recordPage.merge(result);
      } catch (error) {
        console.error(`product template record loadMore err ${error}`);
      } finally {
        this.recordLoading = false;
      }
    },

    /** 渲染用户 */
    renderUserName(userName, staffId) {
      if (isOpenData && staffId) return <strong>{<open-data type="userName" openid={staffId}></open-data>}</strong>;
      return <strong>{userName}</strong>;
    },

    createAttachmentDom(h, attachments, type){
      let attachmentsData = JSON.parse(attachments)
      return attachmentsData && attachmentsData.length > 0
        ? <div class={ `base-timeline-attachment base-file__preview ${type}` }>
          {attachmentsData.map(item => <base-file-item Source={attachmentsData} file={item} key={item.id} readonly size="small"/>)}
        </div>
        : ''
    },

    /** 根据记录的action渲染对应的内容，支持jsx和render函数 */
    renderRecord(h, record) {
      let { action, userName, staffId, content, projectNo, taskNo } = record || {};

      if (action === 'CREATE_PROJECT' || action === 'CANCEL_PROJECT' || action === 'DELETE_PROJECT' || action === 'PRO_UPDATE_WEIGHT') {
        return [
          <i18n path={`common.record.project.action.${action}`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId)}</span>
            <span place="projectId">{projectNo}</span>
          </i18n>,
        ];
      }
      // 审批操作
      if (action === 'APPLY_APPROVE' || action === 'CANCEL_APPROVE' || action === 'PASS_APPROVE' || action === 'REFUSE_APPROVE') {
        return [
          <i18n path={`common.record.project.action.${action}`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId)}</span>
            <span place="projectId">{projectNo}</span>
            <span place="processName">{content.process}</span>
          </i18n>,
          content.remark && <div>{t('common.base.remark')}：<biz-comment-html html={content.remark}></biz-comment-html></div>,content.attachments && this.createAttachmentDom(h, content.attachments),
          content.approveUsers && content.approveUsers[0] && content.approveUsers[0].userName && <div>{t('common.base.approveUser')}：{ this.renderUserName(content.approveUsers[0].userName, content.approveUsers[0].staffId) }</div>,
        ];
      }

      if (action === 'CREATE_TASK' || action === 'DELETE_TASK' || action === 'CANCEL_TASK') {
        return [
          <i18n path={`common.record.project.action.${action}`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId)}</span>
            <span place="taskId">{taskNo}</span>
          </i18n>,
        ];
      }

      if (action === 'EDIT_PROJECT' || action === 'EDIT_TASK') {
        return [
          <i18n path={`common.record.project.action.${action}`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId)}</span>
            <span place="taskId">{taskNo}</span>
            <span place="projectId">{projectNo}</span>
          </i18n>,
          content?.updateFields ? (
            <p>
              {t('common.base.modifyField')}
              {content?.updateFields || ''}
            </p>
          ) : (
            ''
          ),
        ];
      }

      if (action === 'STATE_FLOW') {
        return [
          <i18n path="common.record.project.action.STATE_FLOW" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId)}</span>
            <span place="btnName">{content.buttonName}</span>
            <span place="oldStatus">{content.oldStatusName}</span>
            <span place="newStatus">{content.newStatusName}</span>
          </i18n>,
        ];
      }

      if (action === 'TASK_STATUS_UPDATE') {
        return [
          <i18n path={`common.record.project.action.${action}`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId)}</span>
            <span place="taskId">{taskNo}</span>
            <span place="oldStatus">{statusObj[content.oldStatus]}</span>
            <span place="newStatus">{statusObj[content.newStatus]}</span>
          </i18n>,
        ];
      }

      if (action === 'CON_CREATE_FROM') {
        return [
          <i18n path={`common.record.project.action.${action}`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId)}</span>
            <span place="connectorName">{content.connectorName}</span>
            <span place="toBizTypeName">{content.toBizTypeName}</span>
            <span place="toBizNo">{content.toBizNo}</span>
          </i18n>,
        ];
      }

      if (action === 'CON_CREATE_TO') {
        return [
          <i18n path={`common.record.project.action.${action}`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId)}</span>
            <span place="bizType">{content.bizType}</span>
            <span place="fromBizNo">{content.fromBizNo}</span>
          </i18n>,
        ];
      }

      if (action === 'TIG_CREATE_FROM') {
        return [
          <h5>
            <i18n path="common.record.connector.renderTriggerFrom" >
              <span place="operator">{ this.renderUserName(userName, staffId) } </span>
              <span place="triggerName">{content.triggerName}</span>
              <span place="toBizTypeName">{content.toBizTypeName}</span>
            </i18n>
              。{t('common.label.serialNumber')}：
            <span class="link-text" onClick={() => this.openTriggerTab(content.jumpUrl)}>
              { content.toBizNo }
            </span>
          </h5>
        ];
      }

      if (action === 'TIG_CREATE_TO') {
        return [
         <h5>
          { this.renderUserName(userName, staffId) } 
          &nbsp; {t('common.connector.record.atMainModule')}：
          { content.bizType }
          &nbsp; 
          <i18n path="common.connector.record.triggerMainModuleNoCreateData">
            <span place="data" class="link-text" onClick={() => this.openTriggerTab(content.jumpUrl)}>
              { content.fromBizNo }
            </span>
          </i18n>
          
        </h5>
        ];
      }

      if (action === 'UPDATE_PROGRESS') {
        return [
          <i18n path="common.record.project.action.UPDATE_PROGRESS" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId)}</span>
            <span place="taskNo">{taskNo}</span>
            <span place="oldProgress">{content.oldProgress}</span>
            <span place="newProgress">{content.newProgress}</span>
          </i18n>,
          content?.desc ? (
            <p>
              {t('common.base.updateDescription')}
              {content?.desc || ''}
            </p>
          ) : (
            ''
          ),
        ];
      }

      if (action === 'CREATE_ROLE' || action === 'EDIT_ROLE' || action === 'DELETE_ROLE' || action === 'UPDATE_ROLE_USER') {
        return (
          <i18n path={`common.record.project.action.${action}`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId)}</span>
            <span place="roleName">{content.roleName}</span>
          </i18n>
        )
      }

      if (['FINISH_SATISFATION', 'CREATE_SATISFACTION'].includes(action)) {
        return (
            <div>
              <span>{this.renderUserName(userName, staffId)}</span>
              <span> {content.action}</span>
            </div>
        )
      }
      return [
        <i18n path={`common.record.project.action.${action}`} tag="h5">
          <span place="operator">{this.renderUserName(userName, staffId)}</span>
        </i18n>
      ];
    },
  },
};
</script>
  <style lang="scss" scoped>
.project-type-dynamic-info {
  height: 100%;
  overflow-y: auto;
}
</style>